import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 存储用户数据的简单数据库
let users = [];
const DATA_FILE = 'users.json';

// 尝试从文件加载用户数据
function loadUsers() {
  try {
    if (fs.existsSync(DATA_FILE)) {
      const data = fs.readFileSync(DATA_FILE, 'utf8');
      users = JSON.parse(data);
    }
  } catch (error) {
    console.error('Error loading users data:', error);
    users = [];
  }
}

// 保存用户数据到文件
function saveUsers() {
  try {
    fs.writeFileSync(DATA_FILE, JSON.stringify(users, null, 2));
  } catch (error) {
    console.error('Error saving users data:', error);
  }
}

// 初始化加载用户数据
loadUsers();

// 创建服务器
const server = http.createServer((req, res) => {
  // 设置CORS头
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);

  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  // 解析URL
  const url = req.url;
  const method = req.method;

  // 处理登录请求
  if (url === '/api/login' && method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const { username, password } = JSON.parse(body);
        const user = users.find(u => u.username === username && u.password === password);
        
        res.writeHead(200, { 'Content-Type': 'application/json' });
        if (user) {
          res.end(JSON.stringify({
            success: true,
            message: '登录成功',
            user: {
              id: user.id,
              username: user.username,
              email: user.email
            },
            token: 'mock-jwt-token-' + Date.now()
          }));
        } else {
          res.end(JSON.stringify({
            success: false,
            message: '战士编号或访问密码错误'
          }));
        }
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '请求格式错误' }));
      }
    });
  }
  
  // 处理注册请求
  else if (url === '/api/register' && method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const { username, email, password } = JSON.parse(body);
        
        // 检查用户名是否已存在
        if (users.find(u => u.username === username)) {
          res.writeHead(400, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ success: false, message: '该战士编号已被使用' }));
          return;
        }
        
        // 检查邮箱是否已存在
        if (users.find(u => u.email === email)) {
          res.writeHead(400, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ success: false, message: '该联络邮箱已被注册' }));
          return;
        }
        
        // 创建新用户
        const newUser = {
          id: Date.now().toString(),
          username,
          email,
          password,
          createdAt: new Date().toISOString(),
          premium: false, // 是否付费用户
          premiumExpires: null // 付费到期时间
        };
        
        users.push(newUser);
        saveUsers();
        
        res.writeHead(201, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          success: true,
          message: '战士注册成功',
          user: {
            id: newUser.id,
            username: newUser.username,
            email: newUser.email
          }
        }));
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '请求格式错误' }));
      }
    });
  }
  
  // 处理获取用户信息请求
  else if (url.startsWith('/api/users/') && method === 'GET') {
    const userId = url.split('/')[3];
    const user = users.find(u => u.id === userId);
    
    res.writeHead(200, { 'Content-Type': 'application/json' });
    if (user) {
      res.end(JSON.stringify({
        success: true,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          createdAt: user.createdAt
        }
      }));
    } else {
      res.end(JSON.stringify({ success: false, message: '用户不存在' }));
    }
  }
  
  // 处理购买高级访问权限请求
  else if (url === '/api/purchase' && method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const { userId, paymentMethod } = JSON.parse(body);
        const user = users.find(u => u.id === userId);
        
        if (user) {
          // 模拟支付处理
          // 在实际应用中，这里应该集成真实的支付系统
          user.premium = true;
          // 设置30天的有效期
          const expires = new Date();
          expires.setDate(expires.getDate() + 30);
          user.premiumExpires = expires.toISOString();
          
          saveUsers();
          
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({
            success: true,
            message: '购买成功！您已获得30天的高级访问权限',
            premiumExpires: user.premiumExpires
          }));
        } else {
          res.writeHead(404, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ success: false, message: '用户不存在' }));
        }
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '请求格式错误' }));
      }
    });
  }
  
  // 检查用户是否有高级访问权限
  else if (url === '/api/check-premium' && method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const { userId } = JSON.parse(body);
        const user = users.find(u => u.id === userId);
        
        if (user) {
          const now = new Date();
          const expires = user.premiumExpires ? new Date(user.premiumExpires) : null;
          const hasAccess = user.premium && expires && expires > now;
          
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({
            success: true,
            hasPremiumAccess: hasAccess,
            premiumExpires: user.premiumExpires
          }));
        } else {
          res.writeHead(404, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ success: false, message: '用户不存在' }));
        }
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, message: '请求格式错误' }));
      }
    });
  }
  
  // 处理其他请求 - 提供静态文件
  else {
    // 特殊处理zhenrong.html，需要检查用户是否有权限访问
    if (url === '/zhenrong.html') {
      // 从请求头获取用户ID（在实际应用中，应该通过token验证）
      const userId = req.headers['x-user-id'];
      
      // 如果没有提供用户ID或用户没有付费权限，重定向到支付页面
      if (!userId) {
        // 返回支付页面
        const paymentPagePath = path.join(__dirname, 'payment.html');
        fs.readFile(paymentPagePath, (err, data) => {
          if (err) {
            // 如果支付页面不存在，返回一个简单的HTML支付页面
            const paymentHtml = `
              <!DOCTYPE html>
              <html lang="zh-CN">
              <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>金铲铲之战 - 阵容攻略访问权限</title>
                <style>
                  body {
                    font-family: 'Arial', sans-serif;
                    background: linear-gradient(135deg, #1a0e30 0%, #2e1a4d 100%);
                    color: #ffffff;
                    margin: 0;
                    padding: 0;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    min-height: 100vh;
                    text-align: center;
                  }
                  .payment-container {
                    background: rgba(0, 0, 0, 0.8);
                    padding: 40px;
                    border-radius: 15px;
                    box-shadow: 0 8px 32px rgba(138, 43, 226, 0.3);
                    backdrop-filter: blur(10px);
                    max-width: 500px;
                    width: 90%;
                  }
                  .premium-title {
                    font-size: 2rem;
                    margin-bottom: 20px;
                    background: linear-gradient(45deg, #d4af37, #f8f8f8);
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                  }
                  .price-tag {
                    font-size: 3rem;
                    font-weight: bold;
                    margin: 20px 0;
                    color: #d4af37;
                  }
                  .payment-button {
                    background: linear-gradient(135deg, #d4af37, #ffd700);
                    color: #1a0e30;
                    border: none;
                    padding: 15px 40px;
                    font-size: 1.1rem;
                    font-weight: bold;
                    border-radius: 30px;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    margin-top: 20px;
                  }
                  .payment-button:hover {
                    transform: translateY(-3px);
                    box-shadow: 0 10px 20px rgba(212, 175, 55, 0.4);
                  }
                  .payment-note {
                    margin-top: 30px;
                    font-size: 0.9rem;
                    opacity: 0.8;
                  }
                  .feature-list {
                    text-align: left;
                    margin: 20px 0;
                  }
                  .feature-item {
                    margin: 10px 0;
                    display: flex;
                    align-items: center;
                  }
                  .feature-item:before {
                    content: '✓';
                    color: #d4af37;
                    margin-right: 10px;
                    font-weight: bold;
                  }
                </style>
              </head>
              <body>
                <div class="payment-container">
                  <h1 class="premium-title">高级阵容攻略</h1>
                  <p>解锁独家阵容搭配，提升你的游戏实力！</p>
                  <div class="feature-list">
                    <div class="feature-item">完整阵容模拟器访问权限</div>
                    <div class="feature-item">专业阵容搭配推荐</div>
                    <div class="feature-item">实时版本强势阵容分析</div>
                    <div class="feature-item">30天无限制使用</div>
                  </div>
                  <div class="price-tag">¥9.99</div>
                  <p>购买后立即获得完整访问权限</p>
                  <button class="payment-button" onclick="window.location.href='/login'">登录后购买</button>
                  <p class="payment-note">需要先登录账号才能购买高级访问权限</p>
                </div>
              </body>
              </html>
            `;
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(paymentHtml);
          } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(data);
          }
        });
        return;
      }
      
      // 检查用户是否有付费权限
      const user = users.find(u => u.id === userId);
      const now = new Date();
      const expires = user && user.premiumExpires ? new Date(user.premiumExpires) : null;
      const hasAccess = user && user.premium && expires && expires > now;
      
      if (!hasAccess) {
        // 返回支付页面
        const paymentHtml = `
          <!DOCTYPE html>
          <html lang="zh-CN">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>金铲铲之战 - 阵容攻略访问权限</title>
            <style>
              body {
                font-family: 'Arial', sans-serif;
                background: linear-gradient(135deg, #1a0e30 0%, #2e1a4d 100%);
                color: #ffffff;
                margin: 0;
                padding: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                text-align: center;
              }
              .payment-container {
                background: rgba(0, 0, 0, 0.8);
                padding: 40px;
                border-radius: 15px;
                box-shadow: 0 8px 32px rgba(138, 43, 226, 0.3);
                backdrop-filter: blur(10px);
                max-width: 500px;
                width: 90%;
              }
              .premium-title {
                font-size: 2rem;
                margin-bottom: 20px;
                background: linear-gradient(45deg, #d4af37, #f8f8f8);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
              }
              .price-tag {
                font-size: 3rem;
                font-weight: bold;
                margin: 20px 0;
                color: #d4af37;
              }
              .payment-button {
                background: linear-gradient(135deg, #d4af37, #ffd700);
                color: #1a0e30;
                border: none;
                padding: 15px 40px;
                font-size: 1.1rem;
                font-weight: bold;
                border-radius: 30px;
                cursor: pointer;
                transition: all 0.3s ease;
                margin-top: 20px;
              }
              .payment-button:hover {
                transform: translateY(-3px);
                box-shadow: 0 10px 20px rgba(212, 175, 55, 0.4);
              }
              .payment-note {
                margin-top: 30px;
                font-size: 0.9rem;
                opacity: 0.8;
              }
              .feature-list {
                text-align: left;
                margin: 20px 0;
              }
              .feature-item {
                margin: 10px 0;
                display: flex;
                align-items: center;
              }
              .feature-item:before {
                content: '✓';
                color: #d4af37;
                margin-right: 10px;
                font-weight: bold;
              }
            </style>
          </head>
          <body>
            <div class="payment-container">
              <h1 class="premium-title">高级阵容攻略</h1>
              <p>解锁独家阵容搭配，提升你的游戏实力！</p>
              <div class="feature-list">
                <div class="feature-item">完整阵容模拟器访问权限</div>
                <div class="feature-item">专业阵容搭配推荐</div>
                <div class="feature-item">实时版本强势阵容分析</div>
                <div class="feature-item">30天无限制使用</div>
              </div>
              <div class="price-tag">¥9.99</div>
              <p>购买后立即获得完整访问权限</p>
              <button class="payment-button" id="purchase-btn">立即购买</button>
              <p class="payment-note">购买后将获得30天的高级访问权限</p>
            </div>
            <script>
              document.getElementById('purchase-btn').addEventListener('click', async () => {
                try {
                  const response = await fetch('/api/purchase', {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                      userId: '${userId}',
                      paymentMethod: '模拟支付'
                    })
                  });
                  const result = await response.json();
                  if (result.success) {
                    alert(result.message);
                    window.location.reload();
                  } else {
                    alert('购买失败: ' + result.message);
                  }
                } catch (error) {
                  alert('购买过程中出现错误');
                }
              });
            </script>
          </body>
          </html>
        `;
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(paymentHtml);
        return;
      }
    }
    
    // 对于生产环境，我们需要提供前端构建的文件
    // 这里简化处理，实际项目中应该使用express等框架
    let filePath = path.join(__dirname, url === '/' ? 'index.html' : url);
    
    // 检查文件是否存在
    fs.stat(filePath, (err, stats) => {
      if (err) {
        res.writeHead(404);
        res.end('Not Found');
        return;
      }
      
      // 如果是目录，尝试加载index.html
      if (stats.isDirectory()) {
        filePath = path.join(filePath, 'index.html');
      }
      
      // 读取并提供文件
      fs.readFile(filePath, (err, data) => {
        if (err) {
          res.writeHead(500);
          res.end('Server Error');
          return;
        }
        
        // 设置内容类型
        const extname = path.extname(filePath);
        let contentType = 'text/html';
        switch (extname) {
          case '.js':
            contentType = 'application/javascript';
            break;
          case '.css':
            contentType = 'text/css';
            break;
          case '.json':
            contentType = 'application/json';
            break;
          case '.png':
            contentType = 'image/png';
            break;
          case '.jpg':
            contentType = 'image/jpeg';
            break;
          case '.svg':
            contentType = 'image/svg+xml';
            break;
        }
        
        res.writeHead(200, { 'Content-Type': contentType });
        res.end(data);
      });
    });
  }
});

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`模拟服务器运行在 http://localhost:${PORT}`);
  console.log('可用API端点:');
  console.log('- POST /api/login - 用户登录');
  console.log('- POST /api/register - 用户注册');
  console.log('- GET /api/users/:id - 获取用户信息');
  console.log('- POST /api/purchase - 购买高级访问权限');
  console.log('- POST /api/check-premium - 检查用户是否有高级访问权限');
});